<template>
  <div class="tr-statistics">
    <div class="title">
      <span class="title-text">{{ systemMap[system] }}的流量分布</span>
    </div>
    <div class="date">
      <span class="date-text">起始时间: </span>
      <el-date-picker
        v-model="startDate"
        class="date-style"
        type="date"
        placeholder="选择日期"
        @change="getTrafficStatistics()"
      />
      <span class="date-text">结束时间: </span>
      <el-date-picker
        v-model="endDate"
        class="date-style"
        type="date"
        placeholder="选择日期"
        @change="getTrafficStatistics()"
      />
    </div>
    <div ref="element" class="frame">
      <!-- <loading v-show="runFlag" /> -->
      <div id="charts" />
      <div class="toolbox">
        <span>最大值：</span><em>{{ max }}&nbsp;m³/h</em>
        <span>最小值: </span><em>{{ min }}&nbsp;m³/h</em>
        <span>平均值: </span><em>{{ average }}&nbsp;m³/h</em>
      </div>
    </div>
  </div>
</template>
<script>
// import options from './options/statisticsOption.json'
import 'element-ui/lib/theme-chalk/index.css'
import { mapState } from 'vuex'
import DataSet from '@antv/data-set'
import { Chart } from '@antv/g2'
export default {
  components: {
    // loading: () => import('@components/loading.vue')
  },
  props: {
    system: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      eqmList: {},
      startDate: new Date(new Date().setHours(0, 0, 0, 0)),
      endDate: new Date(),
      // runFlag: false,
      min: null,
      max: null,
      average: null,
      separate: null,
      interval: null,
      options: {},
      systemMap: { 'hcda': 'HCDA', 'lcda': 'LCDA', 'low_chiller': '低温冰机',
        'medium_chiller': '中温冰机' }
    }
  },
  computed: {
    ...mapState({
      service: state => state.service,
      webModel: state => state.authentication.webModel,
      treeTemplate: state => state.component.treeTemplate
    })
    // realOptions() {
    //   if (!this.eqmList) {
    //     return this.options
    //   }
    //   return { ...this.options, series: { ...this.options.series, data: this.eqmList.y }, xAxis: { ...this.options.xAxis, data: this.eqmList.x }}
    // }
  },
  watch: {
    system(val) {
      this.system = val
      this.getTrafficStatistics()
    },
    eqmList: function(val, oldVal) { // 监听data，当发生变化时，触发这个回调函数绘制图表
      this.Chart(val)
    }
  },
  created() {
    this.$nextTick(() => {
      this.getTrafficStatistics()
    })
  },
  methods: {
    sleep(time) {
      return new Promise((resolve) => setTimeout(resolve, time))
    },
    async getTrafficStatistics() {
      if (!this.startDate || !this.endDate) return
      try {
        // this.runFlag = true
        const startDate = Math.round(this.startDate.getTime() / 1000)
        const endDate = Math.round(this.endDate.getTime() / 1000)
        const param = { 'id': this.system, 'begin_time': startDate, 'end_time': endDate }
        const result = await this.service.getTrafficStatistics(param)
        console.log('statistics', result)
        this.eqmList = result.data[0].value
        this.min = Math.round(result.data[0].min_value)
        this.max = Math.round(result.data[0].max_value)
        this.average = Math.round(result.data[0].avg_value)
        if (this.max - this.min) {
          this.separate = Math.round(result.data[0].separate)
          this.interval = Math.round((this.max - this.min) / this.separate)
        } else {
          this.separate = 1
          this.interval = 1000
        }
        await this.sleep(1000)
        if (!result.flag) {
          return
        }
        if (!result.data) {
          return
        }
        if (result.data.length === 0) {
          return
        }
        // this.runFlag = false
      } catch (e) {
        // this.runFlag = false
        this.$notify({
          title: '数据获取出错',
          type: 'error',
          duration: 2500
        })
      }
    },
    Chart(values) {
      document.getElementById('charts').innerHTML = ''
      const data = values.map((value) => {
        return {
          value
        }
      })
      const ds = new DataSet()
      const dv = ds.createView().source(data)
      dv.transform({
        type: 'bin.histogram',
        field: 'value',
        binWidth: this.interval,
        as: ['value', 'count'],
        fill: '#056d76'
      })

      const chart = new Chart({
        container: 'charts',
        autoFit: true,
        padding: [30, 50, 30, 70]
      })
      console.log('data:', data)

      chart.data(dv.rows)
      chart.scale({
        value: {
          min: this.min,
          max: this.max,
          tickInterval: this.interval
        },
        count: {
          // max: 14,
          alias: '数量（个）',
          nice: true
        }
      })
      chart.axis('value', {
        line: {
          lineWidth: 2, // 设置线的宽度
          stroke: '#fff', // 设置线的颜色
          lineDash: [3, 3] // 设置虚线样式
        },
        label: {
          style: {
            textAlign: 'center', // 文本对齐方向，可取值为： start middle end
            fill: '#00f4ff', // 文本的颜色
            textBaseline: 'top' // 文本基准线，可取 top middle bottom，默认为middle
          }
        }

      })
      chart.axis('count', {
        line: {
          lineWidth: 2, // 设置线的宽度
          stroke: '#fff', // 设置线的颜色
          lineDash: [3, 3] // 设置虚线样式
        },
        label: {
          style: {
            fill: '#00f4ff', // 文本的颜色
            fontSize: 12
          }
        },
        title: {
          offset: 30,
          autoRotate: true,
          style: {
            fill: '#00f4ff', // 文本的颜色
            fontSize: 12
          }
        },
        grid: {
          type: 'line',
          lineStyle: {
            stroke: '#fff',
            lineWidth: 1,
            lineDash: [4, 4]
          },
          align: 'center' // 网格顶点从两个刻度中间开始
        }
      })
      chart.tooltip(
        {
          showMarkers: false,
          position: 'top',
          containerTpl: '<div class="g2-tooltip">' +
    // '<div class="g2-tooltip-title" style="margin:10px 0;"></div>' +
    '<ul class="g2-tooltip-list"></ul></div>',
          itemTpl: '<li style="margin:10px 0;">数量： {count}</li>'
        }
      )
      // var margin = 1 / data.length
      chart.scale('value', {
        range: [0, 1],
        tickInterval: this.interval
      })
      // chart.tooltip({
      //   type: 'mini'
      // })
      chart.interval()
        .position('value*count')
        .color('#056d76')
        .tooltip('value*count', (value, count) => {
          return {
            // value: `[${value}]`,
            count: `${count} 个`
          }
        })

      chart.interaction('element-highlight')

      chart.render()
    }
  }
}
</script>
<style lang="scss" scoped>
.tr-statistics{
  display: flex;
  flex-direction: column;
}
.bar-chart{
  flex:1;
}
.date{
  display: flex;
  align-items: center;
  margin-top: 1rem;
}
.title{
  height: 44px;
  margin-left: 4%;
  padding-left: 5px;
  width: 92%;
  background-color: rgba($color: #065ab2, $alpha: 0.3);
  border-style: solid;
  border-left-color: #00f4fe;
  border-top-width: 0;
  border-right-width: 0;
  border-bottom-width: 0;

  // color: white;
  font-weight: bold;
  // font-family:
  font-size: 18px;
  & > .title-text{
    color: white;
    line-height: 44px;
  }
}
.migration-rate {
  padding-top: 10%;
  text-align: center;
}
.date-text{
 color: white;
 font-size: 15px;
 margin-left: 4%;
 margin-right: 1%;
}
.frame{
  position: relative;
  width: 95%;
  height: 90%;
  margin: 0 auto;
}
#charts{
  width: 100%;
  height: 100%;
}
.toolbox{
  position: absolute;
  top: 0;
  right: 3%;
}
.toolbox span{
  color: #00f4ff;
  font-size: 1.2rem;
  margin-left: 1rem;
}
.toolbox em{
  font-size: 1.2rem;
  font-style: normal;
}
</style>
<style lang="scss">
.el-input--prefix .el-input__inner{
  color:white;
  background-color: #05417f  !important;
  border: 1px solid  !important;
  border-color:  #00a8ff !important;
  border-radius: 0;
}
</style>
